package at.tasat.solver.queue;

import at.tasat.solver.Queue;
import at.tasat.solver.VariableOccurencesList;

public final class DynamicVariableOccurencesQueue extends Queue {

	private static final int DEFAULT_THREASHOLD = 20;

	private final int threashold;
	private final VariableComparator comparator;
	private int generations;

	public DynamicVariableOccurencesQueue(int threashold, int numVariables, VariableOccurencesList occurencesList) {
		super(numVariables);
		this.threashold = threashold > 0 ? threashold : DEFAULT_THREASHOLD;
		this.comparator = new VariableComparator(occurencesList);
		generations = 0;
	}

	@Override
	protected int getIndexForEnqueue(int variableId) {
		return size();
	}

	@Override
	protected int getIndexForReenqueue(int variableId) {
		return 0;
	}

	@Override
	protected void onAdded() {
		super.onAdded();
		onChanged();
	}

	@Override
	protected void onRemoved() {
		super.onRemoved();
		onChanged();
	}

	private void onChanged() {
		if (++generations >= threashold) {
			generations = 0;
			sort(comparator);
			assert comparator.isSorted(this);
		}
	}
}
